package com.znsb.msfq.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.znsb.msfq.BaseActivity;
import com.znsb.msfq.R;
import com.znsb.msfq.adapter.AddShowBillAdapter;
import com.znsb.msfq.album.AlbumActivity;
import com.znsb.msfq.album.ViewGalleryActivity;
import com.znsb.msfq.app.ZnsbApp;
import com.znsb.msfq.bean.Bean;
import com.znsb.msfq.utils.CompressImageUtils;
import com.znsb.msfq.utils.DisplayUtil;
import com.znsb.msfq.utils.GsonUtils;
import com.znsb.msfq.utils.HttpUtils;
import com.znsb.msfq.utils.IntentUtils;
import com.znsb.msfq.utils.LogUtils;
import com.znsb.msfq.utils.OnItemClickListener;
import com.znsb.msfq.utils.OverallData;
import com.znsb.msfq.utils.ResponseUtils;
import com.znsb.msfq.utils.ToastUtils;
import com.znsb.msfq.utils.UrlUtils;
import com.znsb.msfq.view.LoadingDialog;
import com.znsb.msfq.view.selectorphoto.Bimp;
import com.znsb.msfq.view.selectorphoto.ImageItem;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name： 添加晒单
 * @author： 孙科技
 * @phone： 13308334117
 * @createTime： 2017/2/13
 * @modifyTime： 2017/2/13
 * @explain：
 */

public class AddShowBillActivity extends BaseActivity implements OnItemClickListener {

    @Bind(R.id.bar_img_back)
    ImageView barImgBack;
    @Bind(R.id.bar_tv_title)
    TextView barTvTitle;
    @Bind(R.id.bar_tv_other)
    TextView barTvOther;
    @Bind(R.id.addbill_edit_content)
    EditText addbillEditContent;
    @Bind(R.id.addbill_tv_num)
    TextView addbillTvNum;
    @Bind(R.id.addbill_ratingbar1)
    RatingBar addbillRatingbar1;
    @Bind(R.id.addbill_ratingbar2)
    RatingBar addbillRatingbar2;
    @Bind(R.id.addbill_ratingbar3)
    RatingBar addbillRatingbar3;
    @Bind(R.id.addbill_tv_commit)
    TextView addbillTvCommit;
    @Bind(R.id.addbill_recyclerview)
    RecyclerView addbillRecyclerview;
    @Bind(R.id.item_re_layout)
    RelativeLayout itemReLayout;

    private AddShowBillAdapter adapter;
    private View view;
    public static LoadingDialog dialog = null;

    @Override
    protected int getlayoutView() {
        return R.layout.act_add_showbill;
    }

    @Override
    protected void initView(View view) {
        goodsId = getIntent().getStringExtra("ids");
        this.view = view;
        popupWidonw();
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        addbillRecyclerview.setLayoutManager(layoutManager);
        adapter = new AddShowBillAdapter(this);
        addbillRecyclerview.setAdapter(adapter);
        barTvTitle.setText("添加晒单");
        adapter.setOnItemClickListener(this);
        addbillEditContent.addTextChangedListener(mTextWatcher);
        addbillEditContent.setSelection(addbillEditContent.length()); // 将光标移动最后一个字符后面
        setLeftCount();
        dialog = new LoadingDialog(this, "加载中...");
    }

    private static final int MAX_COUNT = 150;

    @Override
    protected void initData() {
    }

    private TextWatcher mTextWatcher = new TextWatcher() {

        private int editStart;

        private int editEnd;

        public void afterTextChanged(Editable s) {
            editStart = addbillEditContent.getSelectionStart();
            editEnd = addbillEditContent.getSelectionEnd();

            // 先去掉监听器，否则会出现栈溢出
            addbillEditContent.removeTextChangedListener(mTextWatcher);

            // 注意这里只能每次都对整个EditText的内容求长度，不能对删除的单个字符求长度
            // 因为是中英文混合，单个字符而言，calculateLength函数都会返回1
            while (calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时，进行截断操作
                s.delete(editStart - 1, editEnd);
                editStart--;
                editEnd--;
                ToastUtils.TextToast(ZnsbApp.mContext, "字数超出限制", 2000);
            }
            // mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了，多谢@ainiyidiandian的提醒
            addbillEditContent.setSelection(editStart);

            // 恢复监听器
            addbillEditContent.addTextChangedListener(mTextWatcher);
            setLeftCount();
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

    };

    /**
     * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1
     *
     * @param c
     * @return
     */
    private long calculateLength(CharSequence c) {
        double len = 0;
        for (int i = 0; i < c.length(); i++) {
            int tmp = (int) c.charAt(i);
            if (tmp > 0 && tmp < 127) {
                len += 0.5;
            } else {
                len++;
            }
        }
        return Math.round(len);
    }

    /**
     */
    private void setLeftCount() {
        addbillTvNum.setText(String.valueOf((getInputCount())) + "/" + MAX_COUNT);
    }

    /**
     * 获取用户输入的分享内容字数
     *
     * @return
     */
    private long getInputCount() {
        return calculateLength(addbillEditContent.getText().toString());
    }

    @Override
    protected void clickListener(View view) {

    }

    /**
     * 添加图片的
     */
    private PopupWindow pop;
    private LinearLayout ll_popup;

    private void popupWidonw() {
        pop = new PopupWindow(this);
        View view = getLayoutInflater().inflate(R.layout.select_popupwindow,
                null);
        ll_popup = (LinearLayout) view.findViewById(R.id.select_layout);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view
                .findViewById(R.id.popselect_layout);
        TextView camera = (TextView) view.findViewById(R.id.select_camera);
        TextView picture = (TextView) view.findViewById(R.id.select_picture);
        TextView cancel = (TextView) view.findViewById(R.id.select_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        camera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setPermission2();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        picture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setPermission1();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }

    private int code1 = 100;
    private int code2 = 101;

    private void setPermission1() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    code1);
        } else {
            IntentUtils.startActivityAnimGeneral(AddShowBillActivity.this, AlbumActivity.class, null);
        }

    }

    private void setPermission2() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    code2);
        } else {
            photo();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == code1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                IntentUtils.startActivityAnimGeneral(AddShowBillActivity.this, AlbumActivity.class, null);
            }
        } else if (requestCode == code2) {
            photo();
        }
    }

    /**
     * 调取照相功能返回图片
     */
    private static final int TAKE_PICTURE = 0x000001;
    private Uri mPhotoUri;
    private Intent intent;

    public void photo() {
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues values = new ContentValues();
        mPhotoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
        startActivityForResult(intent, TAKE_PICTURE);
        overridePendingTransition(R.anim.slide_right_in,
                R.anim.slide_left_out);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
                    final Uri uri = mPhotoUri;
                    if (uri != null) {
                        final String[] projection = {MediaStore.Images.Media.DATA};
                        final Cursor cursor = managedQuery(uri, projection, null,
                                null, null);
                        if (cursor.moveToFirst()) {
                            final int columnIndex = cursor
                                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            String imagePath = cursor.getString(columnIndex);
                            ImageItem takePhoto = new ImageItem();
                            takePhoto.setImagePath(imagePath);
                            Bimp.tempSelectBitmap.add(takePhoto);
                            adapter.updateList();
                            refreshView();
                        }
                        if (Integer.parseInt(Build.VERSION.SDK) < 11) {
                            cursor.close();
                        }
                    }
                } else {
                    ToastUtils.TextToast(this, "您取消了操作！", 2000);
                }

                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.bar_img_back, R.id.item_re_layout, R.id.addbill_tv_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_img_back:
                finish();
                break;
            case R.id.item_re_layout:
                ll_popup.startAnimation(AnimationUtils.loadAnimation(
                        AddShowBillActivity.this,
                        R.anim.activity_translate_in));
                pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.addbill_tv_commit:
                String content = addbillEditContent.getText().toString();
                float ratingBar1 = addbillRatingbar1.getRating();
                float ratingBar2 = addbillRatingbar2.getRating();
                float ratingBar3 = addbillRatingbar3.getRating();
                if (!TextUtils.isEmpty(content))
                    addComment(content, ratingBar1, ratingBar2, ratingBar3);
                else
                    ToastUtils.TextToast(ZnsbApp.mContext, "评价不可为空", 2000);
                break;
        }
    }

    /**
     * 添加晒单评价
     *
     * @param content
     * @param ratingBar1
     * @param ratingBar2
     * @param ratingBar3
     */
    private String goodsId = null;

    private void addComment(String content, float ratingBar1, float ratingBar2, float ratingBar3) {
        dialog.show();
        Map<String, Object> maps = new HashMap<>();
        maps.put("goodsId", goodsId);
        maps.put("information", content);
        maps.put("qualitySatisfaction", ratingBar1);
        maps.put("speedSatisfaction", ratingBar2);
        maps.put("serviceSatisfaction", ratingBar3);
        HttpUtils.getInstance(this).postAsnyRequest(UrlUtils.MSFQ_URL_ADDCOMMENT, HttpUtils.getLoginMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String Code, JSONObject request) {
                LogUtils.i("TAG:", "addComment=" + request.toString());
                Bean.ResponseBean data = (Bean.ResponseBean) GsonUtils.getGsonData(Bean.ResponseBean.class, request.toString());
                if (data != null && Bimp.tempSelectBitmap.size() > 0) {
                    uploadFile(data.getModuleId(), data.getModule());
                }
            }

            @Override
            public void onFailure(String result) {

            }
        });
    }

    /**
     * 上传图片
     *
     * @param moduleId
     * @param module
     */
    private void uploadFile(int moduleId, String module) {
        List<File> files = new ArrayList<File>();
        for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
            File file = new File(CompressImageUtils.createFileWithByte(Bimp.tempSelectBitmap.get(0).getImagePath(), i + ""));
            files.add(file);
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("moduleId", moduleId);
        maps.put("module", module);
        HttpUtils.sendMultipart(UrlUtils.MSFQ_URL_UPLOADFILE, HttpUtils.getLoginMaps(maps), files, new ResponseUtils() {
            @Override
            public void onSucceed(String Code, JSONObject request) {
                LogUtils.i("TAG:", "uploadFile=" + request.toString());
                dialog.dismiss();
                ToastUtils.TextToast(ZnsbApp.mContext, "晒单已提交，请等待审核", 2000);
                CompressImageUtils.deletFile();
                OverallData.setReload(1);
                Bimp.tempSelectBitmap.clear();
                finish();
            }

            @Override
            public void onFailure(String result) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.updateList();
        refreshView();
    }

    private void refreshView() {
        ViewGroup.LayoutParams p = itemReLayout.getLayoutParams();
        p.width = DisplayUtil.dip2px(100);
        p.height = DisplayUtil.dip2px(100);
        itemReLayout.setLayoutParams(p);
        if (Bimp.tempSelectBitmap.size() < 3) {
            itemReLayout.setVisibility(View.VISIBLE);
        } else
            itemReLayout.setVisibility(View.GONE);
    }

    @Override
    public void onItemClick(View view, int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("position", "1");
        map.put("ID", position);
        IntentUtils.startActivityAnimGeneral(AddShowBillActivity.this, ViewGalleryActivity.class, map);

    }

}
